<template>
  <Modal v-model="visible" @on-visible-change="changeModal" :title="title" width="800">
    <Form :label-width="110" :model="form" ref="form" :rules="rules">
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="驾驶证" prop="drivingLicencePicUrl">
            <ImageUpload  :images="licenseImg" @on-success="driverLicencePicSucess" ref="driverUpload" action="/base/driver/addDrivingLicencePic" accept="image/png,image/jpeg" :width="96" :disabled="disabled"></ImageUpload>
			 <Input v-model="form.drivingLicencePicUrl"  style="display:none" />
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="头像" prop="headPicUrl">
            <ImageUpload ref="avatarUpload" :images="headImg"  @on-success="headPicSuccess" action="/common/addPic" accept="image/png,image/jpeg" :disabled="disabled"></ImageUpload>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="姓名" prop="driverName">
            <Input v-model="form.driverName"  placeholder="请填写姓名" :maxlength="5" :disabled="model!==0" />
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="工号">
            <Input v-model="form.jobNumber"  placeholder="请填写工号" :disabled="model!==0" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="性别" >
            <RadioGroup v-model="form.sex">
              <Radio :label="0" :disabled="model!==0">男</Radio>
              <Radio :label="1" :disabled="model!==0">女</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="联系电话" prop="tel">
            <Input v-model="form.tel" @on-change="changeTel" placeholder="请填写联系电话" :disabled="model!==0" />
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="身份证号码" prop="idNumber">
            <Input v-model="form.idNumber" placeholder="请填写身份证号码" :disabled="model!==0" />
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="初次领证日期" prop="driverFirstGetTimeDate">
            <DatePicker v-model="form.driverFirstGetTimeDate" type="date" @on-change="changeDate($event,'driverFirstGetTime')"  placeholder="请选择" :disabled="disabled" style="width:100%;"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="12">
          <FormItem label="所属机构"  prop="orgId">
            <Select v-model="form.orgId" placeholder="选择机构" @on-change="orgChange" :disabled="model!==0" :transfer="true">
              <OrgTreeOption></OrgTreeOption>
            </Select>
          </FormItem>
        </Col>
        <Col :md="12">
          <FormItem label="默认车辆" prop="vehicleId">
              <Select v-model="form.vehicleId" :disabled="disabled"  placeholder="请选择车辆" :transfer="true">
                <Option v-for="(v,i) in vehicleList" :key="`sche-vehicle-${v.id}`" :value="v.id">{{v.plateNumber}}</Option>
              </Select>
          </FormItem>
        </Col>
      </Row>
      <Row :gutter="16">
        <Col :md="24">
          <FormItem label="紧急联系人及电话">
            <Input placeholder="请填写紧急联系人及电话" v-model="form.emergencyContact"  :disabled="disabled" />
          </FormItem>
        </Col>
      </Row>

    </Form>
    <div slot="footer">
      <Button type="text" @click="closeModal">取消</Button>
      <Button v-if="!disabled" type="primary" :loading="isModalLoading" @click="submit">保存</Button>
    </div>
  </Modal>
</template>

<script>
import {mapState,mapActions,mapMutations} from 'vuex'
import {post}                             from '@/util/request'
import moment                             from 'moment'
  export default {
    props:{
      value:{type:Boolean},
      model:{type:Number,defautl:0},  // 0：新增，1：查看，2：编辑
    },
    mounted(){

    },
    data(){
      return {
        visible:this.value,
        isModalLoading:false,
        vehicleList:[],
        detail:{},
        form:{id:'',drivingLicencePicUrl:'',headPicUrl:'',sex:0,periodValidity:'',driverStrDate:'',quasiDrivingType:'',driverFirstGetTimeDate:null},
        rules:{
          drivingLicencePicUrl:{required:true,message:'请上传驾驶证',trigger:'change'},
          driverName:{required:true,message:'请输入司机姓名',trigger:'blur'},
          tel:[
            {required:true,message:'请填写司机联系电话',trigger:'blur'},
            {pattern:/^1[3|4|5|7|8][0-9]{9}$/,message:'必须是有效手机号码',trigger:'blur'},
          ],
          idNumber:[
            {required:true,message:'请填写司机身份证',trigger:'blur'},
            {pattern:/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X|x)$/,message:'身份证号码不合法',trigger:'blur'}
          ],
          driverFirstGetTimeDate:{required:true,type:"date",message:'请选择初次领证日期',trigger:'change'},
          orgId:{required:true,message:'请选择所属机构',trigger:'change'}
        },

        headImg:[],
        licenseImg:[]
      };
    },
    watch:{
      value(v){
        this.visible = v;
      },
      visible(v){
        this.$emit('input',v);
      },
      viewData(v){
				this.form = {...v};
				if(v.driverFirstGetTime){
					this.form.driverFirstGetTimeDate =  moment(v.driverFirstGetTime).format('YYYY-MM-DD');
				}
        if (v.headPicUrl){
          this.headImg = [{name:'',url:v.headPicUrl}];
        }
        if (v.drivingLicencePicUrl){
          this.licenseImg=[{name:'',url:v.drivingLicencePicUrl}];
        }
			}
    },
    computed:{
      ...mapState('base',['userinfo']),
      ...mapState('baseinfo/baseinfoDriver',['viewData']),
      title(){
        let title = '查看司机信息';
        switch(this.model){
          case 0: title = '新增司机'; break;
          case 1: title = '查看司机信息'; break;
          case 2: title = '编辑司机信息'; break;
        }
        return title;
      },
      disabled(){
        return this.model === 1;
      },
      disEditable(){
        return this.modal === 2;
      }

    },

    methods:{
      driverLicencePicSucess({file,res}){
        if(res.sta==200){
          let data = res.data;
          this.form={...this.form, ...data};
          file.url = data.drivingLicencePicUrl;
          this.licenseImg = [{name:'',url:data.drivingLicencePicUrl}];
        }
      },
      headPicSuccess({file,res}){
        this.form.headPicUrl=res.data;
        file.url = res.data;
        this.headImg = [{name:'',url:res.data}];
      },
      changeDate(v,f){
					if(v)
						this.form[f] = moment(v).format("YYYY-MM-DD");
					else
						this.form[f] = '';
				},
      orgChange(v){
        if(v){
          this.loadVehicles(v);
        }
      },
      async loadVehicles(orgId){
        let res = await post('/common/findVehicleByOrgId',{'orgIds':orgId});
        this.vehicleList = res.data.data;
      },
      changeModal(v){
        !v && this.closeModal();
      },
      async changeTel(){
        if (this.form.tel.length===11) {
          let res = await post("/base/driver/findDriverByTel",{tel:this.form.tel});
          let detail = res.data.data;
          if (res.data.success && detail !== null){
            if (detail.orgId !== null) {
              return this.$Message.error('手机号码已存在！');
            }
            // detail.orgId = this.form.orgId;
            // if(!detail.drivingLicencePicUrl){
            //   detail.drivingLicencePicUrl = this.form.drivingLicencePicUrl;
            // }
            // if(!detail.headPicUrl){
            //   detail.headPicUrl = this.form.headPicUrl;
            // }
            // this.form = {...this.form, ...detail};
            // 只改id，修改其他信息会有问题。
            this.form.id = detail.id;
            if (detail.drivingLicencePicUrl)
              this.licenseImg = [{name:new Date().getTime(),url:detail.drivingLicencePicUrl}];
            if (detail.headPicUrl)
              this.headImg = [{name:new Date().getTime(),url:detail.headPicUrl}];
          }
        }
      },
      closeModal(){
        this.form =  {id:'',drivingLicencePicUrl:'',headPicUrl:'',sex:0,periodValidity:'',driverStrDate:'',quasiDrivingType:'',driverFirstGetTimeDate:null},
        this.vehicleList = [];
        this.headImg=[];
        this.licenseImg=[];
        this.$refs.driverUpload.reset();
        this.$refs.avatarUpload.reset();
        this.$refs.form.resetFields();
        this.visible=false;
      },
      async submit(){
        let v = await this.$refs.form.validate();
        if (v){
          this.form.driverFirstGetTime=moment(this.form.driverFirstGetTimeDate).format('YYYY-MM-DD');
          if(this.form.driverStrDate!=null){
            this.form.driverStrDate=moment(this.form.driverStrDate).format('YYYY-MM-DD');
          }

          if (this.model === 0) {
            this.submitAdd();
          }
          if (this.model === 2){
            this.submitEdit();
          }
        }
      },
      async submitAdd(){
        this.isModalLoading = true;
  			let res = await post("/base/driver/addDriver",this.form);
        this.isModalLoading = false;
        if (res.data.success){
          this.$Message.success('保存成功');
          this.$emit('add');
          this.closeModal();
        }else{
          this.$Message.error(res.data.msg);
        }
      },
      async submitEdit(){
        this.isModalLoading = true;
        this.form.createtime && delete this.form.createtime;
        let res = await post("/base/driver/updateDriver",this.form);
        this.isModalLoading = false;
        if (res.data.success){
          this.$Message.success('保存成功');
          this.$emit('edit',this.form);
          this.closeModal();
        }else{
          this.$Message.error(res.data.msg);
        }
      }
    }
  }
</script>
